package com.guangfeng.yql.security.global;

import com.guangfeng.yql.comm.bean.R;
import com.guangfeng.yql.security.exception.BusinessException;
import com.guangfeng.yql.security.exception.LoginException;
import com.guangfeng.yql.security.exception.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * token 过期
     *
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public R methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.warn(e.getMessage());
        StringBuilder builder = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error -> builder.append(error.getDefaultMessage()).append("\r\n"));
        return R.parameter_error(builder.toString());
    }

    /**
     * 登录异常
     *
     * @return
     */
    @ExceptionHandler(value = LoginException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public R loginExceptionHandler(LoginException e) {
        log.error("登录异常 : {}", e.getMessage());
        return R.serve_error(e.getMessage());
    }

    /**
     * token 过期
     *
     * @return
     */
    @ExceptionHandler(value = TokenExpiredException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public R tokenExpiredExceptionHandler() {
        log.error("token无效！");
        return R.parameter_error("token 无效");
    }


    /**
     * token 过期
     *
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public R businessExceptionExceptionHandler(BusinessException e) {
        log.error("业务异常 {} ", e.getMessage());
        return R.parameter_error(e.getMessage());
    }

    /**
     * 全局异常处理，将所有的异常处理在后端
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public R bizExceptionHandler(Exception e) {
        log.error("总异常！原因是：{}", e);
        return R.serve_error(e.getMessage());
    }

    /**
     * 全局异常处理，将所有的异常处理在后端
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public R runtimeExceptionHandler(RuntimeException e) {
        log.error("运行时异常！原因是：{}", e);
        return R.serve_error(e.getMessage());
    }


}
